package com.utils;

import com.las.bot.pojo.Comments;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class JsoupUtil {

    //爬虫工具类
    public static List<Comments> spaderJD(String keyWords) throws Exception {
        String url = "https://search.jd.com/Search?keyword=" + keyWords + "&pvid=9045b0472b9f4c17bdf98ec6037a8afc";
        Document document = Jsoup.parse(new URL(url), 30000);
        Element list = document.getElementById("J_goodsList");
        Elements li = list.getElementsByTag("li");
        ArrayList<Comments> commentsArrayList = new ArrayList<>();
        for (Element element : li) {
            String src = element.getElementsByTag("img").attr("src");
            String price = element.getElementsByClass("p-price").eq(0).text();
            String name = element.getElementsByClass("p-name").eq(0).text();
            Comments comments = new Comments();
            comments.setImg(src);
            comments.setPrice(price);
            comments.setName(name);
            commentsArrayList.add(comments);
        }
        return commentsArrayList;
    }

    public static String spader776ByNumber(String number) throws Exception {
        String msg = null;
        String url = "https://www.776dm.com" + number;
        Document document = Jsoup.parse(new URL(url), 30000);
        Element list = document.getElementById("playList");
        Elements pList = list.getElementsByTag("a");
        for (int i = 0; i < pList.size(); i++) {
            if (i == pList.size() - 1) {
                Element element = pList.get(i);
                String href = element.attr("href");
                Document d2 = Jsoup.parse(new URL("https://www.776dm.com" + href), 30000);
                String info = d2.getElementsByTag("h1").html();
                msg = SpiderHtml.guoHtml(info);
                break;
            }
        }
        return msg;
    }

    public static List<String> spader776ListByNumber(String number) throws Exception {
        List<String> msgList = new ArrayList<>();
        String url = "https://www.776dm.com" + number;
        Document document = Jsoup.parse(new URL(url), 30000);
        Element list = document.getElementById("playList");
        Elements pList = list.getElementsByTag("a");
        if (pList.size() > 24) {
            return null;
        }
        for (Element element : pList) {
            String href = element.attr("href");
            Document d2 = Jsoup.parse(new URL("https://www.776dm.com" + href), 30000);
            String info = d2.getElementsByTag("h1").html();
            msgList.add(SpiderHtml.guoHtml(info));
        }
        return msgList;
    }

}